package com.znjc.web.controller.device;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.znjc.common.annotation.Log;
import com.znjc.common.constant.DeviceConstants;
import com.znjc.common.core.controller.BaseController;
import com.znjc.common.core.domain.AjaxResult;
import com.znjc.common.enums.BusinessType;
import com.znjc.device.domain.DeviceBoard;
import com.znjc.device.domain.DeviceBoardRef;
import com.znjc.device.domain.DeviceDevice;
import com.znjc.device.domain.vo.DeviceBoardVO;
import com.znjc.device.domain.vo.PassageVO;
import com.znjc.device.service.IDeviceBoardRefService;
import com.znjc.device.service.IDeviceBoardService;
import com.znjc.device.service.IDeviceDeviceService;
import com.znjc.device.service.IIotSerialService;
import com.znjc.device.util.DataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 【请填写功能名称】Controller
 *
 * @author zengpc
 * @date 2024-01-22
 */
@RestController
@RequestMapping("/device/board/ref")
public class DeviceBoardRefController extends BaseController {

    @Autowired
    private IDeviceBoardRefService deviceBoardRefService;
    @Autowired
    private IDeviceBoardService deviceBoardService;
    @Autowired
    private IDeviceDeviceService deviceDeviceService;
    @Autowired
    private IIotSerialService iotSerialService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 通道转换板
     */
    @PreAuthorize("@ss.hasPermi('device:board:edit')")
    @GetMapping("/list")
    public AjaxResult list(DeviceBoardRef deviceBoardRef) {
        List<DeviceBoard> list = deviceBoardService.list();
        List<DeviceBoardVO> vos = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            //封装所有的板子号，通道号
            list.forEach(board -> {
                DeviceBoardVO vo = new DeviceBoardVO();
                vo.setId(board.getId());
                vo.setBoardCode(Integer.parseInt(board.getBoardCode()));
                vo.setInterestList(DataUtil.getPassageVOs());
                vos.add(vo);
            });
            //排除已经用掉的板子通道号
            LambdaQueryWrapper<DeviceBoardRef> wrapper = new LambdaQueryWrapper();
            //不是导通设备时 排除所有已用的板子通道
            if (StringUtils.isBlank(deviceBoardRef.getDeviceName()) || !deviceBoardRef.getDeviceName().contains("导通")) {
                wrapper.ne(DeviceBoardRef::getDeviceId, deviceBoardRef.getDeviceId());
                List<DeviceBoardRef> yyList = deviceBoardRefService.list(wrapper);
                if (CollectionUtils.isNotEmpty(yyList)) {
                    for (DeviceBoardRef ref : yyList) {
                        Iterator<DeviceBoardVO> iterator = vos.iterator();
                        while (iterator.hasNext()) {
                            DeviceBoardVO vo = iterator.next();
                            if (Integer.parseInt(ref.getBoardCode()) == (vo.getBoardCode())) {
                                Iterator<PassageVO> iteratorp = vo.getInterestList().iterator();
                                while (iteratorp.hasNext()) {
                                    PassageVO pvo = iteratorp.next();
                                    if (ref.getPassageCode().equals(pvo.getCode())) {
                                        iteratorp.remove();
                                        break;
                                    }
                                }
                            }
                            if (CollectionUtils.isEmpty(vo.getInterestList())) {
                                iterator.remove();
                            }
                        }
                    }
                }
            }else{
                //是导通设备时，排除非导通设备占用的板子通道
                List<Long> deviceIds = deviceDeviceService.getIdsByDxbh("02");
                deviceIds.add(deviceBoardRef.getDeviceId());
                wrapper.notIn(DeviceBoardRef::getDeviceId, deviceIds);
                List<DeviceBoardRef> yyList = deviceBoardRefService.list(wrapper);
                if (CollectionUtils.isNotEmpty(yyList)) {
                    for (DeviceBoardRef ref : yyList) {
                        Iterator<DeviceBoardVO> iterator = vos.iterator();
                        while (iterator.hasNext()) {
                            DeviceBoardVO vo = iterator.next();
                            if (Integer.parseInt(ref.getBoardCode()) == (vo.getBoardCode())) {
                                Iterator<PassageVO> iteratorp = vo.getInterestList().iterator();
                                while (iteratorp.hasNext()) {
                                    PassageVO pvo = iteratorp.next();
                                    if (ref.getPassageCode().equals(pvo.getCode())) {
                                        iteratorp.remove();
                                        break;
                                    }
                                }
                            }
                            if (CollectionUtils.isEmpty(vo.getInterestList())) {
                                iterator.remove();
                            }
                        }
                    }
                }
            }
            //已选
            wrapper = new LambdaQueryWrapper();
            wrapper.eq(DeviceBoardRef::getDeviceId, deviceBoardRef.getDeviceId());
            List<DeviceBoardRef> yxList = deviceBoardRefService.list(wrapper);
            if (CollectionUtils.isNotEmpty(yxList)) {
                for (DeviceBoardRef ref : yxList) {
                    for (DeviceBoardVO vo : vos) {
                        if (Integer.parseInt(ref.getBoardCode()) == (vo.getBoardCode())) {
                            vo.getIscheckAll().add(ref.getPassageCode());
                            vo.getInterestListArry().add(ref.getBoardCode() + "_" + ref.getPassageCode());
                            break;
                        }
                    }
                }
            }
        }
        return success(vos);
    }

    @PreAuthorize("@ss.hasPermi('device:board:edit')")
    @Log(title = "设置转换板", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody List<DeviceBoardRef> deviceBoardRefs) {
        if (CollectionUtils.isNotEmpty(deviceBoardRefs)) {
            Long deviceId = deviceBoardRefs.get(0).getDeviceId();
            if (null == deviceId) {
                return error("无设备信息");
            }
            LambdaQueryWrapper<DeviceBoardRef> wrapper = new LambdaQueryWrapper();
            wrapper.eq(DeviceBoardRef::getDeviceId, deviceId);
            List<DeviceBoardRef> list = deviceBoardRefService.list(wrapper);
            deviceBoardRefService.remove(wrapper);
            if (StringUtils.isNotBlank(deviceBoardRefs.get(0).getBoardCode())) {
                deviceBoardRefService.saveBatch(deviceBoardRefs);
                String addressBitmap = "";
                for (DeviceBoardRef ref : deviceBoardRefs) {
                    addressBitmap += ref.getBoardCode() + ref.getPassageCode() + ",";
                }
                addressBitmap = addressBitmap.substring(0, addressBitmap.length() - 1);
                if (deviceId.intValue() == 0) {
                    //设置公共点
                    addressBitmap = addressBitmap.replaceAll(","," ");
                    String command = "f1 83 00 03 07 01" + addressBitmap;
                    iotSerialService.sendCommand(getDeptId(), command, "设置公共点");
                    redisTemplate.opsForValue().set(DeviceConstants.GGD,addressBitmap);
                } else {
                    DeviceDevice device = deviceDeviceService.getById(deviceId);
                    if (null != device) {
                        device.setAddressBitmap(addressBitmap);
                        deviceDeviceService.updateById(device);
                        addressBitmap = addressBitmap.replaceAll(","," ");
                        //设置设备测量点
                        String command = "f1 83 00 04 " + device.getDxbh() + " 02 " + addressBitmap;
                        iotSerialService.sendCommand(device.getDeptId(), command, "设置" + device.getDeviceName() + "点位");
                    }
                }
            } else {
                DeviceDevice device = deviceDeviceService.getById(deviceId);
                if (null != device) {
                    device.setAddressBitmap("");
                    deviceDeviceService.updateById(device);
                    if (CollectionUtils.isNotEmpty(list)) {
                        /**
                         * K、删除指定点的端口配置
                         * 平台下发
                         * f1 85 00 04 0C 02 01 12 xx xx
                         * 00 04 帧数据长度
                         * 0c 删除指定点的端口
                         * 02 长度
                         * 01 原端口配置类型  附表五 ，1 接地电阻 若此值是0 设备按C1P1自动搜素
                         * 12 	C1P1端口地址
                         */
                        list.stream().forEach(ref -> {
                            iotSerialService.sendCommand(device.getDeptId(), "f1 85 00 04 0C 02 01 " + ref.getBoardCode() + ref.getPassageCode(), "删除" + ref.getBoardCode() + ref.getPassageCode() + "的端口配置");
                        });
                    }
                }
            }
        }
        return toAjax(true);
    }
}
